<!-- 授权 -->
<template>
  <view style="margin: 20px">
    <u--form
      labelPosition="left"
      :model="data.userInfo"
      :rules="data.rules"
      ref="dataForm"
    >
      <!-- 头像上传区域 -->
      <view class="avatar-upload-container">
        <view style="margin-top: 15px">
          <u--image
            :showLoading="true"
            :src="userInfo.avatar_show"
            width="80px"
            height="80px"
            shape="circle"
          ></u--image>
        </view>
      </view>

      <u-button @click="state.on_of = true">打开微信授权</u-button>
      <u-form-item label="昵称" prop="nickname" borderBottom labelWidth="auto">
        <u--input
          v-model="data.userInfo.nickname"
          border="none"
          inputAlign="right"
          disabled
        ></u--input>
      </u-form-item>
      <div style="margin: 10px 50px">
        <u-button
          type="primary"
          text="修改用户信息"
          @click="submit"
          :loading="loading"
        />
      </div>
    </u--form>
    <u-wx-auth
      ref="wxAuthRef"
      :show="state.on_of"
      :logo="state.logo"
      :title="state.title"
      :tips="tips"
      :confirm-text="state.confirmText"
      @choose-avatar="onChooseAvatar"
      @confirm="onConfirm"
      @close="state.on_of = false"
    ></u-wx-auth>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, toRefs } from "vue";
import { getLoginInfo, putLoginInfo } from "../../api/userInfo";
import { showToast } from "../../utils/toast";
import { getResource } from "../../utils/Resource.js";
// 表单引用
const dataForm = ref(null);
// 上传相关
const fileList = ref([]);
const uploadUrl = "https://dian18.cn/upload/image";
const loading = ref(false);

const state = reactive({
  title: "",
  logo: "",
  on_of: false,
  confirmText: "确认授权",
});
state.title = import.meta.env.VITE_API_TITLE;
// 表单数据
const data = reactive({
  userInfo: {
    avatar: "", // 头像服务器存储地址
    avatar_show: "", // 头像显示地址
    nickname: "", // 昵称
  },
  rules: {},
});
const { userInfo } = toRefs(data);

// 初始化用户信息
const init = async () => {
  try {
    const res = await getLoginInfo();
    if (res.data) {
      // 更新头像显示
      const avatarShow = res.data.avatar_show
        ? res.data.avatar_show
        : "/static/logo.png";

      fileList.value = [{ url: avatarShow }];
      userInfo.value.avatar_show = avatarShow;
      userInfo.value.nickname = res.data.nickname || "";
      userInfo.value.avatar = res.data.avatar || "";
    }
  } catch (error) {
    console.error("初始化失败:", error);
    fileList.value = [{ url: "/static/logo.png" }];
  }
};

// 上传文件到服务器
const uploadFilePromise = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: "file",
      header: {
        Authorization: "Bearer " + uni.getStorageSync("token"),
      },
      formData: {
        file_type: "2",
        type: "avatar",
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code == 10000 && data.data?.url) {
          resolve(data.data.url);
        } else {
          reject(new Error(data.msg || "上传失败"));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

// 提交用户信息修改
const submit = async () => {
  loading.value = true;
  try {
    const res = await putLoginInfo(userInfo.value);
    showToast(res.message);
  } catch (error) {
    showToast("提交失败，请重试");
    console.error("提交失败:", error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时初始化数据
onMounted(() => {
  init();
});

const onChooseAvatar = async (e) => {
  try {
    const tempUrl = e;
    if (!tempUrl) {
      showToast("获取头像失败");
      return;
    }
    // 上传临时头像到服务器
    const result = await uploadFilePromise(tempUrl);

    console.log(e);
    console.log(result);

    // console.log(result);
    userInfo.value.avatar = result;
    userInfo.value.avatar_show = getResource(result);
  } catch (err) {
    showToast("获取头像失败，请重试");
  }
};
const onConfirm = (data) => {
  userInfo.value.nickname = data.nickname;
  console.log(userInfo.value);

  state.on_of = false;
};
</script>

<style scoped lang="scss">
:deep(.u-upload__deletable) {
  top: 7px !important;
  right: 12px !important;
  border-radius: 50% !important;
}
:deep(.u-upload__deletable__icon) {
  top: 1px !important;
  right: 2px !important;
}
:deep(.u-button__text) {
  font-size: 15px !important;
  font-weight: bolder;
}
:deep(.u-upload__wrap) {
  justify-content: center;
}

.avatar-upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.avatar-img {
  border: 1px solid #eee;
}

.upload-btn {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 5px 10px;
  background-color: #f5f5f5;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;

  &:active {
    background-color: #e8e8e8;
  }
}

.upload-text {
  font-size: 14px;
  color: #333;
}
</style>
